/**
 * 使用Lambdas和Streams
 * Stream是对集合的包装,通常和lambda一起使用。
 * 使用lambdas可以支持许多操作,如 map, filter, limit, sorted, count, min, max, sum, collect 等等。
 * 同样,Stream使用懒运算,他们并不会真正地读取所有数据,遇到像getFirst() 这样的方法就会结束链式语法。
 * 在接下来的例子中,我们将探索lambdas和streams 能做什么。
 * 我们创建了一个Person类并使用这个类来添加一些数据到list中,将用于进一步流操作。
 */
package lambda;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.joining;

public class LambdaStreamTest {
    private static List<Person> javaProgrammers = null;
    private static List<Person> phpProgrammers = null;

    public static void main(String[] args) {
        initData();
        forEachTest(javaProgrammers, phpProgrammers);
    }

    private static void initData() {
        javaProgrammers = new ArrayList<Person>() {
            {
                add(new Person("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000));
                add(new Person("Tamsen", "Brittany", "Java programmer", "female", 23, 1500));
                add(new Person("Floyd", "Donny", "Java programmer", "male", 33, 1800));
                add(new Person("Sindy", "Jonie", "Java programmer", "female", 32, 1600));
                add(new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200));
                add(new Person("Maude", "Jaimie", "Java programmer", "female", 27, 1900));
                add(new Person("Shawn", "Randall", "Java programmer", "male", 30, 2300));
                add(new Person("Jayden", "Corrina", "Java programmer", "female", 35, 1700));
                add(new Person("Palmer", "Dene", "Java programmer", "male", 33, 2000));
                add(new Person("Addison", "Pam", "Java programmer", "female", 34, 1300));
            }
        };
        phpProgrammers = new ArrayList<Person>() {
            {
                add(new Person("Jarrod", "Pace", "PHP programmer", "male", 34, 1550));
                add(new Person("Clarette", "Cicely", "PHP programmer", "female", 23, 1200));
                add(new Person("Victor", "Channing", "PHP programmer", "male", 32, 1600));
                add(new Person("Tori", "Sheryl", "PHP programmer", "female", 21, 1000));
                add(new Person("Osborne", "Shad", "PHP programmer", "male", 32, 1100));
                add(new Person("Rosalind", "Layla", "PHP programmer", "female", 25, 1300));
                add(new Person("Fraser", "Hewie", "PHP programmer", "male", 36, 1100));
                add(new Person("Quinn", "Tamara", "PHP programmer", "female", 21, 1000));
                add(new Person("Alvin", "Lance", "PHP programmer", "male", 38, 1600));
                add(new Person("Evonne", "Shari", "PHP programmer", "female", 40, 1800));
            }
        };
    }

    private static void printList(List<Person> list) {
        list.forEach(System.out::println);
    }

    private static void forEachTest(List<Person> javaProgrammers, List<Person> phpProgrammers) {
        //现在我们使用forEach方法来迭代输出上述列表
        System.out.println("所有程序员的姓名:");
        javaProgrammers.forEach(p -> {
            System.out.printf("%s %s; ", p.getFirstName(), p.getLastName());
        });
        javaProgrammers.forEach(p -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));
        phpProgrammers.forEach(p -> System.out.printf("%s %s; ", p.getFirstName(), p.getLastName()));

        //我们同样使用forEach方法,增加程序员的工资5%:
        System.out.println("给程序员加薪 5% :");
        Consumer<Person> giveRaise = e -> e.setSalary(e.getSalary() / 100 * 5 + e.getSalary());
        javaProgrammers.forEach(giveRaise);
        phpProgrammers.forEach(giveRaise);
        printList(javaProgrammers);
        printList(phpProgrammers);

        //另一个有用的方法是过滤器filter() ,让我们显示月薪超过1400美元的PHP程序员:
        phpProgrammers.stream()
                .filter(p -> (p.getSalary() > 1400))
                .forEach(p -> System.out.printf("%s %s\n", p.getFirstName(), p.getSalary()));

        System.out.println("下面是年龄大于 24岁且月薪在$1,400以上的女PHP程序员:");
        //定义filters
        Predicate<Person> ageFilter = (p) -> (p.getAge() > 25);
        Predicate<Person> salaryFilter = (p) -> (p.getSalary() > 1400);
        Predicate<Person> genderFilter = person -> ("female".equals(person.getGender()));
        phpProgrammers.stream()
                .filter(ageFilter)
                .filter(salaryFilter)
                .filter(genderFilter)
                .forEach(person -> System.out.printf("%s %s\n", person.getFirstName(), person.getLastName()));
        System.out.println("年龄大于24岁的女性Java Programmers");
        javaProgrammers.stream()
                .filter(ageFilter)
                .filter(genderFilter)
                .forEach(person -> System.out.printf("%s %s\n", person.getFirstName(), person.getLastName()));

        //使用limit方法，可以限制结果集个数
        System.out.println("最前面的3个Java Programmers:");
        javaProgrammers.stream()
                .limit(3)
                .forEach(person -> System.out.printf("%s %s\n", person.getFirstName(), person.getLastName()));
        System.out.println("最前面的3个女性Java Programmers:");
        javaProgrammers.stream()
                .filter(genderFilter)
                .limit(3)
                .forEach(person -> System.out.printf("%s %s\n", person.getFirstName(), person.getLastName()));
        //根据名字和薪水排序Java程序员,放到一个list中,然后显示列表
        System.out.println("根据name排序，并显示前5个Java Programmers:");
        List<Person> sortedJavaProgrammers = javaProgrammers.stream()
                .sorted((p, p2) -> (p.getFirstName().compareTo(p2.getFirstName())))
                .limit(5)
                .collect(Collectors.toList());
        printList(sortedJavaProgrammers);
        System.out.println("根据salary排序Java Programmers:");
        sortedJavaProgrammers = javaProgrammers.stream()
                .sorted((p, p2) -> (p.getSalary() - p2.getSalary()))
                .collect(Collectors.toList());
        printList(sortedJavaProgrammers);
        //如果我们只对最低和最高的薪水感兴趣,比排序后选择第一个/最后一个 更快的是min和max方法
        System.out.println("工资最低的 Java Programmer:");
        Person pers = javaProgrammers.stream()
                .min((p, p2) -> (p.getSalary() - p2.getSalary()))
                .get();
        System.out.println(pers.toString());
        System.out.println("工资最高的 Java Programmer:");
        Person pers2 = javaProgrammers.stream()
                .max((p, p2) -> (p.getSalary() - p2.getSalary()))
                .get();
        System.out.println(pers2.toString());

        // 结合 map 方法,我们可以使用 collect 方法来将我们的结果集放到一个字符串,一个 Set 或一个TreeSet中
        System.out.println("将PHP Programmers 的 firstName 拼接成字符串：");
        String phpDevelops = phpProgrammers
                .stream()
                .map(Person::getFirstName)
                .collect(joining(" ; "));// 在进一步的操作中可以作为标记(token)
        System.out.println(phpDevelops);
        System.out.println("将Java Programmer的firstName存放到set");
        Set<String> javaDevFirstName = javaProgrammers
                .stream()
                .map(Person::getFirstName)
                .collect(Collectors.toSet());

        System.out.println("将Java Programmer的lastName存放到TreeSet");
        TreeSet<String> javaDevLastName = javaProgrammers
                .stream()
                .map(Person::getLastName)
                .collect(Collectors.toCollection(TreeSet::new));

        //Streams 还可以是并行的(parallel)。 示例如下:
        System.out.print("计算付给Java Programmers的所有money：");
        int totalSalary = javaProgrammers
                .parallelStream()
                .mapToInt(p -> p.getSalary())
                .sum();
        System.out.println(totalSalary);

        //我们可以使用summaryStatistics方法获得stream 中元素的各种汇总数据。 接下来,我们可以访问这些方法,比如getMax, getMin, getSum或getAverage:
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        IntSummaryStatistics statistics = numbers
                .stream()
                .mapToInt(x -> x)
                .summaryStatistics();
        System.out.println("List中最大的数字：" + statistics.getMax());
        System.out.println("List中最小的数字：" + statistics.getMin());
        System.out.println("List所有数字总和：" + statistics.getSum());
        System.out.println("所有数字的平均值：" + statistics.getAverage());


        IntSummaryStatistics statisticsJavaSalary = javaProgrammers
                .stream()
                .mapToInt(person -> person.getSalary())
                .summaryStatistics();
        System.out.println("javaProgrammers中工资最多为：" + statisticsJavaSalary.getMax());
        System.out.println("javaProgrammers中工资最少为：" + statisticsJavaSalary.getMin());
        System.out.println("javaProgrammers中所有人工资和为：" + statisticsJavaSalary.getSum());
        System.out.println("javaProgrammers所有人工资平均值：" + statisticsJavaSalary.getAverage());
    }
}

class Person {

    private String firstName, lastName, job, gender;
    private int salary, age;

    public Person(String firstName, String lastName, String job,
                  String gender, int age, int salary) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.gender = gender;
        this.age = age;
        this.job = job;
        this.salary = salary;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", job='" + job + '\'' +
                ", gender='" + gender + '\'' +
                ", salary=" + salary +
                ", age=" + age +
                '}';
    }
}